package com.lz.seata.controller;

import com.lz.seata.domain.CodeMsg;
import com.lz.seata.domain.Product;
import com.lz.seata.domain.ResultVO;
import com.lz.seata.service.IProductService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: ProductController
 * @Date: 2020/5/4 11:40
 * @Author: LiZhen
 * @Version: 1.0
 */
@RestController
public class ProductController {
    @Resource
    private IProductService productService;

    @GetMapping("/products/{id}")
    public ResultVO find(@PathVariable Integer id) {
        System.out.println("ProductController.find");
        try {
            Product product = productService.findById(id);
            return ResultVO.success(product);
        } catch (Exception e) {
            return ResultVO.error(CodeMsg.Gone);
        }
    }

    @GetMapping("/products/deductStock/{id}/{number}")
    public ResultVO deductStock(@PathVariable Integer id, @PathVariable Integer number) {
        try {
            productService.deductStock(id, number);
            return ResultVO.success(CodeMsg.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.error(CodeMsg.CREATED_ERROR);

        }
    }

    @GetMapping("/products/testloadbalance")
    public ResultVO testLoadBalance(HttpServletRequest request) {
        Map map = new HashMap<>();
        map.put("requestPort", request.getServerPort());
        return ResultVO.success(map);
    }
}
